//
//  PlayerViewController.m
//  A段项目前期
//
//  Created by 杨利佳 on 15/5/20.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "PlayerViewController.h"
#import "MusicModel.h"
#import "ConnectModel.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <STKAudioPlayer.h>
#import "Singleton.h"
#import "PlayView.h"
#import <AVFoundation/AVFoundation.h>

@interface PlayerViewController ()

@property (nonatomic, copy) NSString *playUrl;
@property (nonatomic, retain) Singleton *sin;
@property (nonatomic, retain) NSTimer *time;
@property (nonatomic, retain) CABasicAnimation *rotationAnimation;
@property (nonatomic ,retain) NSDictionary *dic;
@property (nonatomic, retain) PlayView *play;

@end

@implementation PlayerViewController

- (void)dealloc
{
    [_play release];
    [_dic release];
    [_sin release];
    [_time release];
    [_rotationAnimation release];
    [_trackId release];
    [_playUrl release];
    [super dealloc];
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.sin = [Singleton shareManager];
        
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self connect:self.trackId];
    self.time = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(progressAction) userInfo:nil repeats:YES];
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];

}


#pragma mark - slider的事件
- (void)progressAction
{
    Singleton *singer = [Singleton shareManager];
    
    NSInteger currentTimeSec = singer.streamer.progress / 60;
    NSInteger currentTimeMin = (NSInteger)singer.streamer.progress % 60;
    
    NSInteger songTimeSec = singer.streamer.duration / 60;
    NSInteger songTimeMin = (NSInteger)singer.streamer.duration % 60;
    
    self.play.currentTime.text = [NSString stringWithFormat:@"%ld:%ld", (long)currentTimeSec, (long)currentTimeMin];
    self.play.songTime.text = [NSString stringWithFormat:@"%ld:%ld", (long)songTimeSec, (long)songTimeMin];
    self.play.slider.value = singer.streamer.progress / singer.streamer.duration;
    if (singer.streamer.progress > 0) {
        if (singer.streamer.progress > (singer.streamer.duration - 1)) {
            [_time invalidate];
            self.play.slider.value = 0;
            self.time = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(progressAction) userInfo:nil repeats:YES];
            [self nextAction:nil];
            
        }
    }
    
}

// 网络请求,对视图赋值
- (void)connect:(NSNumber *)trackId
{
    [self.play removeFromSuperview];
    self.play = [[PlayView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:_play];
    [_play release];
    
    [_play.back addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 网络请求
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@", trackId];
    [ConnectModel connectWithUrl:str block:^(NSData *data) {
        self.dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        if (self.array) {
            [defaults setValue:self.array forKey:@"array"];
        }

        [defaults setObject:_dic forKey:@"dict"];
        
        _play.title.text = [_dic objectForKey:@"title"];
        [_play.backImage sd_setImageWithURL:[NSURL URLWithString:[_dic objectForKey:@"coverLarge"]] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
        [_play.show sd_setImageWithURL:[NSURL URLWithString:[_dic objectForKey:@"coverLarge"]] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
        
        // 本界面的播放路径
        self.playUrl = [_dic objectForKey:@"playUrl64"];
        [self start:nil];
        
        // 播放按钮
        [_play.start setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
        [_play.start addTarget:self action:@selector(start:) forControlEvents:UIControlEventTouchUpInside];
        
        // 上一首
        [_play.last addTarget:self action:@selector(lastAction:) forControlEvents:UIControlEventTouchUpInside];
        // 下一首
        [_play.next addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
        
        
        // 头像小logo
        NSDictionary *smallDic = [_dic objectForKey:@"userInfo"];
        [_play.head sd_setImageWithURL:[smallDic objectForKey:@"smallLogo"] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
        
        // 主播名字
        _play.personName.text = [smallDic objectForKey:@"nickname"];
        
        // 路径数量
        _play.tracks.text = [NSString stringWithFormat:@"声音 %@", [smallDic objectForKey:@"tracks"]];
        
        // 粉丝数量
        _play.followers.text = [NSString stringWithFormat:@"粉丝 %@ ", [smallDic objectForKey:@"followers"]];
        
        // 主播描述
        _play.personDescribe.text = [smallDic objectForKey:@"personDescribe"];

    }];
    
}

// 返回按钮
- (void)backAction:(id)sender
{
    NSArray *arr = self.view.window.subviews;
    UIView *myView = [arr objectAtIndex:2];
    myView.hidden = NO;
    [self dismissViewControllerAnimated:YES completion:nil];
}


// 上一首
- (void)lastAction:(id)sender
{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
     NSArray *arr = [def objectForKey:@"array"];
    int num = 0;
    for (NSDictionary *di in arr) {
        if ([[di objectForKey:@"playUrl64"] isEqualToString:_playUrl]) {
            break;
        }
        num++;
    }
    NSNumber *track = [[NSNumber alloc] init];
    if (arr.count) {
        if (num > 0) {
            
            track = [[arr objectAtIndex:num - 1] objectForKey:@"trackId"];
        }else if (num == 0){
            track = [[arr lastObject] objectForKey:@"trackId"];
        }
        self.play.slider.value = 0;
        [self connect:track];

    }
        // 这里千万不能release，会崩溃
//    [track release];
}

- (void)nextAction:(id)sender
{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSArray *arr = [def objectForKey:@"array"];

    int num = 0;
    for (NSDictionary *di in arr) {
        if ([[di objectForKey:@"playUrl64"] isEqualToString:_playUrl]) {
            break;
        }
        num++;
    }
    
    NSNumber *track = [[NSNumber alloc] init];
    if (arr.count) {
        if (num < arr.count - 1) {
            
            track = [[arr objectAtIndex:num + 1] objectForKey:@"trackId"];
            
        } else if (num == arr.count - 1){
            track = [[arr firstObject] objectForKey:@"trackId"];
        }
        self.play.slider.value = 0;
        [self connect:track];
        // 这里track不能release，会崩溃
        
    }
}


// 播放(暂停)按钮
- (void)start:(id)sender
{
    NSArray *arr = self.view.window.subviews;
    UIView *myView = [arr objectAtIndex:2];
    UIButton *mainButton = [myView.subviews objectAtIndex:0];
    myView.hidden = YES;
    
    self.rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    _rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0];
    _rotationAnimation.duration = 10;
    _rotationAnimation.repeatCount = 100000;

    
    // 判断是否和上次点击时为同一首歌,若是同一首歌,判断播放还是暂停
    if ([self.playUrl isEqualToString:_sin.url]) {
        if ([_sin.state isEqualToString:@"playing"]) {
            [_sin.streamer pause];
            _sin.state = nil;
            [sender setImage:[UIImage imageNamed:@"play86.png"]forState:UIControlStateNormal];
            [mainButton.layer removeAnimationForKey:@"rotation"];
            
        }  else {
            [_sin.streamer resume];
            _sin.state = @"playing";
            [sender setImage:[UIImage imageNamed:@"pause.png"]forState:UIControlStateNormal];
            [mainButton.layer addAnimation:_rotationAnimation forKey:@"rotation"];
        }
        
        // 如果不是同一首歌, 则直接进行初始化进行播放
    } else {
        [_sin playWithUrl:self.playUrl];
        _sin.state = @"playing";
        _sin.url = _playUrl;
        [sender setImage:[UIImage imageNamed:@"pause.png"]forState:UIControlStateNormal];
        UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
        [image sd_setImageWithURL:[NSURL URLWithString:[_dic objectForKey:@"coverLarge"]]];
        [mainButton addSubview:image];
        [mainButton.layer addAnimation:_rotationAnimation forKey:@"rotation"];
        
    }
    
    [self transform];
    
}

// 图片转动动画
- (void)transform
{
    if ([_sin.state isEqualToString:@"playing"]) {
        [_play.show.layer addAnimation:_rotationAnimation forKey:@"rotation"];
    } else
    {
        [_play.show.layer removeAnimationForKey:@"rotation"];
    }
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
